const app = getApp()

const checkImgSecurity = async function (params) {
  try {
    const {
      result
    } = await wx.cloud.callFunction({
      name: "security",
      data: params
    })
    return result
  } catch (error) {
    return {
      errCode: 20313
    }
  }
}
export const uploadSecurityImg = async function (params) {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: params.count ? params.count : 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async function (res) {
        wx.showLoading({
          title: '正在识别',
        })
        const filePathArr = res.tempFilePaths
        let bufferArr = []
        let fileArr = []
        let promiseArr = []
        // 上传图片
        for (let i = 0; i < filePathArr.length; i++) {
          promiseArr.push(new Promise((reslove, reject) => {
            wx.getFileSystemManager().readFile({
              filePath: filePathArr[i], //选择图片返回的相对路径
              success: async buffer => { //成功的回调

                let result = {}

                if (app.globalData.identification) {

                  result = await checkImgSecurity({
                    file: buffer.data
                  })
  

                } else {

                  result = {errCode: 0}

                }




                console.log("鉴别结果", result)
                if (result.errCode !== 0) {
                  wx.showToast({
                    title: "图片内容包含敏感信息",
                    icon: "none"
                  })
                  // reslove()
                } else {
                  reslove({
                    file: filePathArr[i],
                    buffer: buffer.data
                  })
                }
              }
            })
          }))

        }
        const promiseAll = await Promise.all(promiseArr)
        console.log("结果", promiseAll)
        wx.hideLoading()
        resolve(promiseAll)
      },
      fail: e => {
        reject(e)
      }
    })
  })

}